package com.control.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public final class HttpDownloader {
	
	private URL url = null;
	/**
	 *
	 */
	public  String downLoad(String urlStr){
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			while((line = buffer.readLine())!=null){
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(buffer!=null){
					buffer.close();
					buffer = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	/**
	 * 
	 * @param urlStr
	 * @param path
	 * @param fileName
	 * @return
	 */
	public int downFile(String urlStr,String path,String fileName){
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();
			if(fileUtils.isFileExist(fileName,path)){
				return 1;
			}else{
				inputStream = getInputStreamFromUrl(urlStr);
				File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
				if(resultFile == null){
					return -1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}finally{
			try {
				if(inputStream != null){
					inputStream.close();
					inputStream = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	/**
	 * 
	 * @param urlStr
	 * @return
	 * @throws IOException
	 */
	
	public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}
	public static void main(String[] args) {
		System.out.println("111111111111111111111123");
		//System.out.println(HttpDownloader.downLoad("d://DateTest.java"));
	}
}
